package com.fingard.dsp.bank.directbank.nnbill01.wsdl.batch;

import com.bill99.schema.commons.Version;
import com.bill99.schema.fo.commons.Pay2bankTypeV2;
import com.bill99.schema.fo.commons.RequestHeader;
import com.bill99.schema.fo.settlement.*;
import com.fingard.constant.Format;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 批量付款工具类
 * */
public class CustomerUtil {
	
	private static final String ENCODING = "utf-8";

	/**
	 * BatchSettlementApplyRequest转换为xml格式
	 * @param request 付款请求（原文）
	 * @return String xml 字符串
	 */
	public static String batchSettlementApplyRequestToXml(BatchSettlementApplyRequest request) {
		StringBuilder reqXml = new StringBuilder();
		reqXml.append("<tns:batch-settlement-apply-request xmlns:ns0=\"http://www.99bill.com/schema/commons\" xmlns:ns1=\"http://www.99bill.com/schema/fo/commons\" xmlns:tns=\"http://www.99bill.com/schema/fo/settlement\">");
		reqXml.append("<tns:request-header>");
		reqXml.append("<tns:version xmlns:tns=\"http://www.99bill.com/schema/fo/commons\">");
		reqXml.append("<ns0:version>" + request.getRequestHeader().getVersion().getVersion() + "</ns0:version>");
		reqXml.append("<ns0:service>" + request.getRequestHeader().getVersion().getService() + "</ns0:service>");
		reqXml.append("</tns:version>");
		reqXml.append("<ns1:time>" + request.getRequestHeader().getTime() + "</ns1:time>");
		reqXml.append("</tns:request-header>");
		reqXml.append("<tns:request-body>");
		reqXml.append("<tns:payer-acctCode>" + request.getRequestBody().getPayerAcctCode() + "</tns:payer-acctCode>");
		reqXml.append("<tns:batch-no>" + request.getRequestBody().getBatchNo() + "</tns:batch-no>");
		reqXml.append("<tns:apply-date>" + request.getRequestBody().getApplyDate() + "</tns:apply-date>");
		reqXml.append("<tns:name>" + request.getRequestBody().getName() + "</tns:name>");
		reqXml.append("<tns:total-amt>" + request.getRequestBody().getTotalAmt() + "</tns:total-amt>");
		reqXml.append("<tns:total-cnt>" + request.getRequestBody().getTotalCnt() + "</tns:total-cnt>");
		reqXml.append("<tns:fee-type>" + request.getRequestBody().getFeeType() + "</tns:fee-type>");
		reqXml.append("<tns:cur>" + request.getRequestBody().getCur() + "</tns:cur>");
		reqXml.append("<tns:checkAmt-cnt>" + request.getRequestBody().getCheckAmtCnt() + "</tns:checkAmt-cnt>");
		reqXml.append("<tns:batch-fail>" + request.getRequestBody().getBatchFail() + "</tns:batch-fail>");
		reqXml.append("<tns:recharge-type>" + request.getRequestBody().getRechargeType() + "</tns:recharge-type>");
		reqXml.append("<tns:auto-refund>" + request.getRequestBody().getAutoRefund() + "</tns:auto-refund>");
		reqXml.append("<tns:phoneNote-flag>" + request.getRequestBody().getPhoneNoteFlag() + "</tns:phoneNote-flag>");
		reqXml.append("<tns:merchant-memo1>" + request.getRequestBody().getMerchantMemo1() + "</tns:merchant-memo1>");
		reqXml.append("<tns:merchant-memo2>" + request.getRequestBody().getMerchantMemo2() + "</tns:merchant-memo2>");
		reqXml.append("<tns:merchant-memo3>" + request.getRequestBody().getMerchantMemo3() + "</tns:merchant-memo3>");
		reqXml.append("<tns:pay2bank-list>");
		for (int i = 0; i < request.getRequestBody().getPay2bankLists().size(); i++) {
			Pay2bankTypeV2 pay2bank = request.getRequestBody().getPay2bankLists().get(i);
			reqXml.append("<tns:pay2bank>");
			reqXml.append("<ns1:merchant-id>" + pay2bank.getMerchantId() + "</ns1:merchant-id>");
			reqXml.append("<ns1:amt>" + pay2bank.getAmt() + "</ns1:amt>");
			reqXml.append("<ns1:bank>" + pay2bank.getBank() + "</ns1:bank>");
			reqXml.append("<ns1:name>" + pay2bank.getName() + "</ns1:name>");
			reqXml.append("<ns1:bank-card-no>" + pay2bank.getBankCardNo() + "</ns1:bank-card-no>");
			reqXml.append("<ns1:branch-bank>" + pay2bank.getBranchBank() + "</ns1:branch-bank>");
			reqXml.append("<ns1:payee-type>" + pay2bank.getPayeeType() + "</ns1:payee-type>");
			reqXml.append("<ns1:province>" + pay2bank.getProvince() + "</ns1:province>");
			reqXml.append("<ns1:city>" + pay2bank.getCity() + "</ns1:city>");
			reqXml.append("<ns1:memo>" + pay2bank.getMemo() + "</ns1:memo>");
			reqXml.append("<ns1:bank-purpose>" + pay2bank.getBankPurpose() + "</ns1:bank-purpose>");
			reqXml.append("<ns1:bank-memo>" + pay2bank.getBankMemo() + "</ns1:bank-memo>");
			reqXml.append("<ns1:payee-note>" + pay2bank.getPayeeNote() + "</ns1:payee-note>");
			reqXml.append("<ns1:payee-mobile>" + pay2bank.getPayeeMobile() + "</ns1:payee-mobile>");
			reqXml.append("<ns1:payee-email>" + pay2bank.getPayeeEmail() + "</ns1:payee-email>");
			reqXml.append("<ns1:period>" + pay2bank.getPeriod() + "</ns1:period>");
			reqXml.append("<ns1:merchant-memo1>" + pay2bank.getMerchantMemo1() + "</ns1:merchant-memo1>");
			reqXml.append("<ns1:merchant-memo2>" + pay2bank.getMerchantMemo2() + "</ns1:merchant-memo2>");
			reqXml.append("<ns1:merchant-memo3>" + pay2bank.getMerchantMemo3() + "</ns1:merchant-memo3>");
			reqXml.append("</tns:pay2bank>");
		}
		reqXml.append("</tns:pay2bank-list>");
		reqXml.append("</tns:request-body>");
		reqXml.append("</tns:batch-settlement-apply-request>");
		String reqSoap = reqXml.toString();
		return reqSoap;
	}

	/**
	 * BatchidQueryRequest转换为xml格式
	 * @param request 查询请求(根据批次号batchNo查询)
	 * @return String xml 字符串
	 */
	public static String batchidQueryRequestToXml(BatchidQueryRequest request) {
		StringBuilder reqXml = new StringBuilder();
		reqXml.append("<tns:batchid-query-request xmlns:ns0=\"http://www.99bill.com/schema/commons\" xmlns:ns1=\"http://www.99bill.com/schema/fo/commons\" xmlns:tns=\"http://www.99bill.com/schema/fo/settlement\">");
		reqXml.append("<tns:request-header>");
		reqXml.append("<tns:version xmlns:tns=\"http://www.99bill.com/schema/fo/commons\">");
		reqXml.append("<ns0:version>" + request.getRequestHeader().getVersion().getVersion() + "</ns0:version>");
		reqXml.append("<ns0:service>" + request.getRequestHeader().getVersion().getService() + "</ns0:service>");
		reqXml.append("</tns:version>");
		reqXml.append("<ns1:time>" + request.getRequestHeader().getTime() + "</ns1:time>");
		reqXml.append("</tns:request-header>");
		reqXml.append("<tns:request-body>");
		reqXml.append("<tns:batch-no>" + request.getRequestBody().getBatchNo() + "</tns:batch-no>");
		reqXml.append("<tns:page>1</tns:page>");
		reqXml.append("<tns:page-size>10</tns:page-size>");
		reqXml.append("<tns:list-flag>0</tns:list-flag>");
		reqXml.append("</tns:request-body>");
		reqXml.append("</tns:batchid-query-request>");
		String reqSoap = reqXml.toString();
		return reqSoap;
	}

	/**
	 * SettlementPkiApiRequest转换为xml格式 
	 * @param request 付款请求（密文）
	 * @return String xml 字符串
	 */
	public static String settlementPkiApiRequestToXml(SettlementPkiApiRequest request) {
		StringBuilder reqXml = new StringBuilder();
		reqXml.append("<?xml version='1.0' encoding='UTF-8'?>");
		reqXml.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">");
		reqXml.append("<soapenv:Body>");
		reqXml.append("<tns:settlement-pki-api-request xmlns:ns0=\"http://www.99bill.com/schema/commons\" xmlns:ns1=\"http://www.99bill.com/schema/fo/commons\" xmlns:tns=\"http://www.99bill.com/schema/fo/settlement\">");
		reqXml.append("<tns:request-header>");
		reqXml.append("<tns:version xmlns:tns=\"http://www.99bill.com/schema/fo/commons\">");
		reqXml.append("<ns0:version>" + request.getRequestHeader().getVersion().getVersion() + "</ns0:version>");
		reqXml.append("<ns0:service>" + request.getRequestHeader().getVersion().getService() + "</ns0:service>");
		reqXml.append("</tns:version>");
		reqXml.append("<ns1:time>" + request.getRequestHeader().getTime() + "</ns1:time>");
		reqXml.append("</tns:request-header>");
		reqXml.append("<tns:request-body>");
		reqXml.append("<tns:member-code>" + request.getRequestBody().getMemberCode() + "</tns:member-code>");
		reqXml.append("<tns:data>");
		reqXml.append("<ns1:original-data/>");
		reqXml.append("<ns1:signed-data>" + request.getRequestBody().getData().getSignedData() + "</ns1:signed-data>");
		reqXml.append("<ns1:encrypted-data>" + request.getRequestBody().getData().getEncryptedData() + "</ns1:encrypted-data>");
		reqXml.append("<ns1:digital-envelope>" + request.getRequestBody().getData().getDigitalEnvelope() + "</ns1:digital-envelope>");
		reqXml.append("</tns:data>");
		reqXml.append("</tns:request-body>");
		reqXml.append("</tns:settlement-pki-api-request>");
		reqXml.append("</soapenv:Body>");
		reqXml.append("</soapenv:Envelope>");
		String reqSoapEnv = reqXml.toString();
		return reqSoapEnv;
	}

	/**
	 * 把请求信息数据设置到BatchSettlementApplyRequest类中
	 * @param dealInfo 请求信息数据
	 * @return BatchSettlementApplyRequest 请求付款信息类(原文)
	 */
	public static BatchSettlementApplyRequest getBatchSettlementApplyRequest(DealInfoEntity dealInfo) {
		BatchSettlementApplyRequest request = new BatchSettlementApplyRequest();
		RequestHeader head = new RequestHeader();
		Version ve = new Version();
		head.setTime(Format.DateTime14Format.format(new Date()));
		ve.setService(dealInfo.getServiceType());
		ve.setVersion(dealInfo.getVersion());
		head.setVersion(ve);
		request.setRequestHeader(head);
		ApplyRequestType body = new ApplyRequestType();
		body.setApplyDate(dealInfo.getApplyDate()==null?"":dealInfo.getApplyDate());
		body.setAutoRefund(dealInfo.getAutoRefund()==null?"":dealInfo.getAutoRefund());
		body.setBatchFail(dealInfo.getBatchFail()==null?"":dealInfo.getBatchFail());
		body.setBatchNo(dealInfo.getBatchNo()==null?"":dealInfo.getBatchNo());
		body.setCheckAmtCnt(dealInfo.getCheckAmtCnt()==null?"":dealInfo.getCheckAmtCnt());
		body.setCur(dealInfo.getCur()==null?"":dealInfo.getCur());
		body.setFeeType(dealInfo.getFeeType()==null?"":dealInfo.getFeeType());
		body.setMerchantMemo1(dealInfo.getMerchantMemo1()==null?"":dealInfo.getMerchantMemo1());
		body.setMerchantMemo2(dealInfo.getMerchantMemo2()==null?"":dealInfo.getMerchantMemo2());
		body.setMerchantMemo3(dealInfo.getMerchantMemo3()==null?"":dealInfo.getMerchantMemo3());
		body.setName(dealInfo.getName()==null?"":dealInfo.getName());
		body.setPayerAcctCode(dealInfo.getPayerAcctCode()==null?"":dealInfo.getPayerAcctCode());
		body.setPhoneNoteFlag(dealInfo.getPhoneNoteFlag()==null?"":dealInfo.getPhoneNoteFlag());
		body.setRechargeType(dealInfo.getRechargeType()==null?"":dealInfo.getRechargeType());
		body.setTotalAmt(dealInfo.getTotalAmt()==null?"":dealInfo.getTotalAmt());
		body.setTotalCnt(dealInfo.getTotalCnt()==null?"":dealInfo.getTotalCnt());
		body.setPay2bankLists(getPay2BankList(dealInfo));
		request.setRequestBody(body);
		return request;
	}

	/**
	 * 把请求查询信息数据设置到BatchidQueryRequest类中
	 * @param dealInfo 请求信息数据
	 * @return BatchidQueryRequest 请求查询信息类(原文）
	 */
	public static BatchidQueryRequest getBatchidQueryRequest(DealInfoEntity dealInfo) {
		BatchidQueryRequest request = new BatchidQueryRequest();
		RequestHeader head = new RequestHeader();
		Version ve = new Version();
		head.setTime(Format.DateTime14Format.format(new Date()));
		ve.setService(dealInfo.getServiceType());
		ve.setVersion(dealInfo.getVersion());
		head.setVersion(ve);
		request.setRequestHeader(head);
		BatchidQueryRequestType body = new BatchidQueryRequestType();
		body.setBatchNo(dealInfo.getBatchNo()==null?"":dealInfo.getBatchNo());
		body.setListFlag(dealInfo.getListFlag()==null?"":dealInfo.getListFlag());
		body.setPage(dealInfo.getPage()==null?"":dealInfo.getPage());
		body.setPageSize(dealInfo.getPageSize()==null?"":dealInfo.getPageSize());
		request.setRequestBody(body);
		return request;
	}

	/**
	 * 把付款详细信息设置到Pay2bankTypeV2类中，并且保存在LIST列表表
	 * @param dealInfo 付款请求信息数据
	 * @return List<Pay2bankTypeV2> 保存有付款信息的列表类
	 */
	public static List<Pay2bankTypeV2> getPay2BankList(DealInfoEntity dealInfo) {
		List<Pay2bankTypeV2> list = new ArrayList<Pay2bankTypeV2>();
		List<OrderInfoEntity> batchUpLoadBeanList = dealInfo.getOrdersInfo();
			for (OrderInfoEntity orderDto : batchUpLoadBeanList) {
				Pay2bankTypeV2 pay2bankType = new Pay2bankTypeV2();
				pay2bankType.setAmt(orderDto.getAmt()==null?"":orderDto.getAmt());
				pay2bankType.setBank(orderDto.getBank()==null?"":orderDto.getBank());
				pay2bankType.setBankCardNo(orderDto.getBankCardNo()==null?"":orderDto.getBankCardNo());
				pay2bankType.setBankMemo(orderDto.getBankMemo()==null?"":orderDto.getBankMemo());
				pay2bankType.setBankPurpose(orderDto.getBankPurpose()==null?"":orderDto.getBankPurpose());
				pay2bankType.setBranchBank(orderDto.getBranchBank()==null?"":orderDto.getBranchBank());
				pay2bankType.setCity(orderDto.getCity()==null?"":orderDto.getCity());
				pay2bankType.setMemo(orderDto.getMemo()==null?"":orderDto.getMemo());
				pay2bankType.setMerchantId(orderDto.getMerchantId()==null?"":orderDto.getMerchantId());
				pay2bankType.setMerchantMemo1(orderDto.getMerchantMemo1()==null?"":orderDto.getMerchantMemo1());
				pay2bankType.setMerchantMemo2(orderDto.getMerchantMemo2()==null?"":orderDto.getMerchantMemo2());
				pay2bankType.setMerchantMemo3(orderDto.getMerchantMemo3()==null?"":orderDto.getMerchantMemo3());
				pay2bankType.setName(orderDto.getName()==null?"":orderDto.getName());
				pay2bankType.setPayeeEmail(orderDto.getPayeeEmail()==null?"":orderDto.getPayeeEmail());
				pay2bankType.setPayeeMobile(orderDto.getPayeeMobile()==null?"":orderDto.getPayeeMobile());
				pay2bankType.setPayeeNote(orderDto.getPayeeNote()==null?"":orderDto.getPayeeNote());
				pay2bankType.setPayeeType(orderDto.getPayeeType()==null?"":orderDto.getPayeeType());
				pay2bankType.setPeriod(orderDto.getPeriod()==null?"":orderDto.getPeriod());
				pay2bankType.setProvince(orderDto.getProvince()==null?"":orderDto.getProvince());
				list.add(pay2bankType);
			}
		return list;
	}

	/**
	 * 生成报盘文件
	 * @param request 请求报文
	 * @param dealInfo 请求信息
	 * @return String 返回文件完整信息，包括文件路径
	 * */
	public static String fileRequest(SettlementPkiApiRequest request, DealInfoEntity dealInfo) {
		BufferedOutputStream io = null;
		String filename = "INBOUND_" + dealInfo.getMemberCode() + "_"
				+ Format.DateTime14Format.format(new Date()) + "_"
				+ dealInfo.getBatchNo() + ".PKI";
		try {
			File name = new File(filename);
			if (name.exists()) {
				name.delete();
				name.createNewFile();
			} else {
				name.createNewFile();
			}
			filename = name.getAbsolutePath();
			String org = CustomerUtil.settlementPkiApiRequestToXml(request);
			io = new BufferedOutputStream(new FileOutputStream(name));
			io.write(org.getBytes("utf-8"));
			System.out.println(filename);
			return filename;
		} catch (IOException e) {
			e.printStackTrace();
			return filename;
		} finally {
			if (io != null) {
				try {
					io.flush();
					io.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
